﻿using MusicPlayerPlus.Interface.Base;
using MusicPlayerPlus.Interface.Model.Muisc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MusicPlayerPlus.PlugIn.OpenFile
{
    public class PlugIn : InterfaceBase,
        //Input
        MusicPlayerPlus.Interface.Base.Action.Input.IAutoExecuteAction,
        //Output
        MusicPlayerPlus.Interface.Base.Action.Output.IAddMusicListAction,
        MusicPlayerPlus.Interface.Base.Action.Output.IAddToMenuAction,
        MusicPlayerPlus.Interface.Base.Action.Output.IGetMusicListAction
    {

        /// <summary>
        /// 自动执行动作接口
        /// </summary>
        public void AutoExecute()
        {
            AddToMenu_Action("打开文件", () =>
            {
                OpenFile();
            });
        }
        /// <summary>
        /// 添加列表
        /// </summary>
        public Action<IList<MusicItem>> AddMusicList_Action { private get; set; }

        /// <summary>
        /// 添加菜单动作接口
        /// </summary>
        public Action<string, System.Action> AddToMenu_Action { private get; set; }

        /// <summary>
        /// 获取列表
        /// </summary>
        public Func<IList<MusicItem>> GetMusicList_Action { private get; set; }

        private void OpenFile()
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Multiselect = true;
            openFileDialog.Filter = "mp3|*.mp3";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                IList<MusicItem> musicList = GetMusicList_Action();

                string[] file = openFileDialog.FileNames;

                foreach (var item in file)
                {
                    MusicItem newitem = new MusicItem()
                    {
                        ID = Guid.NewGuid(),
                        Name = System.IO.Path.GetFileName(item),
                        Location = item,
                        Type = Interface.Model.Enum.MusicSourceType.Local,
                        Cove = "pack://siteoforigin:,,,./default.png"
                    };
                    if (!IsExistList(musicList, newitem))
                    {
                        musicList.Add(newitem);
                    }
                }
                AddMusicList_Action(musicList);
            }
        }

        private bool IsExistList(IList<MusicItem> musicList, MusicItem musicItem)
        {
            foreach (var item in musicList)
            {
                if (item.Location.ToLower() == musicItem.Location.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
    }
}
